<template>
    <a-spin :spinning="formLoading">
        <j-form-container :disabled="formDisabled">
            <!-- 主表单区域 -->
            <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
                <a-row>
                    <a-col :span="8">
                        <a-form-model-item label="预定类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bookType">
                            <j-dict-select-tag type="list" v-model="model.bookType" dictCode="book_type"
                                placeholder="请输入预定类型(散客/团体)" />
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-model-item label="预定人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bookPerson">
                            <a-input v-model="model.bookPerson" placeholder="请输入预定人"></a-input>
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-model-item label="预定时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bookDate">
                            <j-date v-model="model.bookDate" :showTime="true" dateFormat="YYYY-MM-DD HH:mm:ss"
                                style="width: 100%;" />
                        </a-form-model-item>
                    </a-col>

                </a-row>
                <a-row>
                    <a-col :span="8">
                        <a-form-model-item label="联系电话" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="photo">
                            <a-input v-model="model.photo" placeholder="请输入联系电话"></a-input>
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-model-item label="客户单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="company">
                            <a-input v-model="model.company" placeholder="请输入客户单位"></a-input>
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-model-item label="账户类型(vip)" :labelCol="labelCol" :wrapperCol="wrapperCol"
                            prop="accountType">
                            <j-dict-select-tag type="list" v-model="model.accountType" dictCode="account_type"
                                placeholder="请请输入账户类型(vip)" />
                        </a-form-model-item>
                    </a-col>

                </a-row>
                <a-row>
                    <!-- <a-col :span="8">
                        <a-form-model-item label="预订状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bookStatus">
                            <a-input v-model="model.bookStatus" placeholder="请输入预订状态"></a-input>
                        </a-form-model-item>
                    </a-col> -->
                    <!-- <a-col :span="6">
                        <a-form-model-item label="预抵店时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="dateArrival">
                            <j-date v-model="model.dateArrival" :showTime="true" dateFormat="YYYY-MM-DD HH:mm:ss"
                                style="width: 100%;" :allowClear="false" />
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-model-item label="预离店时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="dateDeparture">
                            <j-date v-model="model.dateDeparture" :showTime="true" dateFormat="YYYY-MM-DD HH:mm:ss"
                                style="width: 100%;" :allowClear="false" />
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-model-item label="房晚数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="dateNum">
                            <a-input-number v-model="model.dateNum" placeholder="自动计算" style="width: 100%" disabled />
                        </a-form-model-item>
                    </a-col> -->
                    <a-col :span="8">
                        <a-form-model-item label="优惠理由" :labelCol="labelCol" :wrapperCol="wrapperCol"
                            prop="discountReason">
                            <a-input v-model="model.discountReason" placeholder="请输入优惠理由"></a-input>
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-model-item label="预订单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                            <a-input v-model="model.bookCode" placeholder="系统自动生成" disabled></a-input>
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                            <a-input v-model="model.remark" placeholder="请输入备注"></a-input>
                        </a-form-model-item>
                    </a-col>
                </a-row>
            </a-form-model>
        </j-form-container>
        <a-divider style="font-weight: bold;">预定房间明细</a-divider>
        <!-- 子表单区域 -->
        <j-vxe-table keep-source ref="roomBookInfoMx" :loading="roomBookInfoMxTable.loading"
            :columns="roomBookInfoMxTable.columns" :dataSource="roomBookInfoMxTable.dataSource" :maxHeight="300"
            :disabled="formDisabled" :rowNumber="true" :rowSelection="true" :toolbar="true"
            :linkage-config="linkRoomTypeCodeConfig" @valueChange="handleValueChange" rowSelectionType="radio"
            size="small" bordered />
        <!-- <a-tabs v-model="activeKey" @change="handleChangeTabs">
            <a-tab-pane tab="预订单明细信息" :key="refKeys[0]" :forceRender="true">
                <j-vxe-table keep-source :ref="refKeys[0]" :loading="roomBookInfoMxTable.loading"
                    :columns="roomBookInfoMxTable.columns" :dataSource="roomBookInfoMxTable.dataSource" :maxHeight="300"
                    :disabled="formDisabled" :rowNumber="true" :rowSelection="true" :toolbar="true"
                    :linkage-config="linkRoomTypeCodeConfig" @valueChange="handleValueChange" rowSelectionType="radio"
                    size="small" bordered />
            </a-tab-pane>
        </a-tabs> -->
    </a-spin>
</template>

<script>
import { getAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import dayjs from 'dayjs'

export default {
    name: 'YuDingGuanLiForm',
    mixins: [JVxeTableModelMixin],
    components: {
        JFormContainer,
    },
    data() {
        return {
            dayjs,
            linkRoomTypeCodeConfig: [
                { requestData: this.loadRoomTypeCode, key: 'roomTypeCode', },
            ],
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
            model: {
                bookDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
                dateArrival: dayjs().add(1, 'day').format('YYYY-MM-DD') + ' 12:00:00',
                dateDeparture: dayjs().add(2, 'day').format('YYYY-MM-DD') + ' 12:00:00',
                dateNum: 1
            },
            formLoading: false,
            // 新增时子表默认添加几行空数据
            addDefaultRowNum: 0,
            validatorRules: {
                bookType: [{ required: true, message: '请完善内容' }],
                bookPerson: [{ required: true, message: '请完善内容' }],
                bookDate: [{ required: true, message: '请完善内容' }],
                photo: [{ required: true, message: '请完善内容' }],
                dateArrival: [{ validator: this.validateDateArrival, trigger: 'change' }, { required: true, message: '请完善内容' }],
                dateDeparture: [{ validator: this.validateDateDeparture, trigger: 'change' }, { required: true, message: '请完善内容' }],
                dateNum: [{ required: true, message: '请完善内容' }],
            },
            refKeys: ['roomBookInfoMx',],
            tableKeys: ['roomBookInfoMx',],
            activeKey: 'roomBookInfoMx',
            // 预订单明细信息
            roomBookInfoMxTable: {
                loading: false,
                dataSource: [],
                columns: [
                    {
                        title: '房间类型',
                        key: 'roomTypeCode',
                        type: JVXETypes.select,
                        width: "180px",
                        placeholder: '${title}',
                        linkageKey: 'checkInMode',
                        validateRules: [{ required: true, message: '${title}不能为空' }]
                    },
                    {
                        title: '预抵店时间',
                        key: 'dateArrival',
                        type: JVXETypes.datetime,
                        width: "185px",
                        defaultValue: dayjs().add(0, 'day').format('YYYY-MM-DD') + ' 12:00:00',
                        validateRules: [
                            { required: true, message: '${title}不能为空' },
                            {
                                handler({ cellValue, row, column }, callback, target) {
                                    if (dayjs(cellValue).isAfter(dayjs(row.dateDeparture))) {
                                        callback(false, '抵店时间不能晚于离店时间') // false = 未通过，可以跟自定义提示
                                    } else {
                                        callback(true) // true = 通过验证
                                    }
                                },
                                message: '${title}默认提示'
                            }
                        ]
                    },
                    {
                        title: '预离店时间',
                        key: 'dateDeparture',
                        type: JVXETypes.datetime,
                        width: "185px",
                        defaultValue: dayjs().add(1, 'day').format('YYYY-MM-DD') + ' 12:00:00',
                        validateRules: [
                            { required: true, message: '${title}不能为空' },
                            {
                                handler({ cellValue, row, column }, callback, target) {
                                    if (cellValue.split(' ')[1] !== '12:00:00') {
                                        callback(false, '离店时间必须是12点整') // false = 未通过，可以跟自定义提示
                                    } else {
                                        callback(true) // true = 通过验证
                                    }
                                },
                                message: '${title}默认提示'
                            },
                            {
                                handler({ cellValue, row, column }, callback, target) {
                                    if (dayjs(cellValue).isBefore(dayjs(row.dateArrival))) {
                                        callback(false, '离店时间不能早于抵店时间') // false = 未通过，可以跟自定义提示
                                    } else {
                                        callback(true) // true = 通过验证
                                    }
                                },
                                message: '${title}默认提示'
                            }
                        ]
                    },
                    {
                        title: '房晚数',
                        key: 'dateNum',
                        type: JVXETypes.inputNumber,
                        width: "100px",
                        placeholder: '请输入${title}',
                        defaultValue: 1,
                        disabled: true,
                        validateRules: [
                            { required: true, message: '${title}不能为空' },
                            {
                                handler({ cellValue, row, column }, callback, target) {
                                    if (cellValue < 1) {
                                        callback(false, '房晚数不能小于1') // false = 未通过，可以跟自定义提示
                                    } else {
                                        callback(true) // true = 通过验证
                                    }
                                },
                                message: '${title}默认提示'
                            }
                        ]
                    },
                    {
                        title: '入住模式',
                        key: 'checkInMode',
                        type: JVXETypes.select,
                        width: "160px",
                        placeholder: '${title}',
                    },
                    {
                        title: '是否加床',
                        key: 'isExtraBed',
                        type: JVXETypes.select,
                        width: "120px",
                        placeholder: '${title}',
                        dictCode: "is_true",
                        defaultValue: '否',
                        validateRules: [{ required: true, message: '${title}不能为空' }]
                    },
                    {
                        title: '加床费',
                        key: 'extraBedAmount',
                        type: JVXETypes.inputNumber,
                        width: "140px",
                        placeholder: '请输入${title}',
                        defaultValue: 0,
                    },
                    {
                        title: '早餐份数',
                        key: 'breakfastNum',
                        type: JVXETypes.input,
                        width: "120px",
                        placeholder: '${title}',
                        defaultValue: '',
                    },
                    {
                        title: '预定房间数',
                        key: 'bookRoomNum',
                        type: JVXETypes.inputNumber,
                        width: "140px",
                        placeholder: '${title}',
                        defaultValue: 1,
                    },
                    {
                        title: '额定房价',
                        key: 'ratedHousePrice',
                        type: JVXETypes.input,
                        width: "140px",
                        placeholder: '${title}',
                        defaultValue: '',
                        disabled: true,
                        validateRules: [{ required: true, message: '${title}不能为空' }]
                    },
                    {
                        title: '折扣',
                        key: 'discount',
                        type: JVXETypes.inputNumber,
                        width: "120px",
                        placeholder: '${title}',
                        defaultValue: 1,
                        validateRules: [{ required: true, message: '${title}不能为空' }]
                    },
                    {
                        title: '房价',
                        key: 'roomPrice',
                        type: JVXETypes.inputNumber,
                        width: "140px",
                        placeholder: '${title}',
                        defaultValue: 0,
                        disabled: true,
                        validateRules: [{ required: true, message: '${title}不能为空' }]
                    },
                    {
                        title: '房间号',
                        key: 'roomCode',
                        type: JVXETypes.input,
                        disabled: true,
                        width: "200px",
                        placeholder: '请输入${title}',
                        defaultValue: '',
                    },

                ]
            },
            url: {
                add: "/room/roomBookInfo/add",
                edit: "/room/roomBookInfo/edit",
                queryById: "/room/roomBookInfo/queryById",
                roomBookInfoMx: {
                    list: '/room/roomBookInfo/queryRoomBookInfoMxByMainId'
                },
            },
            rowRoomFlagList: null,
        }
    },
    props: {
        //表单禁用
        disabled: {
            type: Boolean,
            default: false,
            required: false
        }
    },
    computed: {
        formDisabled() {
            return this.disabled
        },
    },
    methods: {
        validateDateArrival(rule, value, callback) {
            if (dayjs(value).isAfter(dayjs(this.model.dateDeparture))) {
                callback(new Error('入住时间不能晚于离店时间'))
            } else {
                if (this.model.dateDeparture) {
                    this.$refs.form.validateField('dateDeparture')
                }
                const startDay = dayjs(this.model.dateArrival)
                const endDay = dayjs(this.model.dateDeparture)
                this.model.dateNum = endDay.diff(startDay, 'day') < 1 ? 1 : endDay.diff(startDay, 'day')
                callback()
            }
        },
        validateDateDeparture(rule, value, callback) {
            if (dayjs(value).isBefore(dayjs(this.model.dateArrival))) {
                callback(new Error('离店时间不能早于入住时间'))
            } else {
                if (this.model.dateArrival) {
                    this.$refs.form.validateField('dateArrival')
                }
                const startDay = dayjs(this.model.dateArrival)
                const endDay = dayjs(this.model.dateDeparture)
                this.model.dateNum = endDay.diff(startDay, 'day') < 1 ? 1 : endDay.diff(startDay, 'day')
                callback()
            }
        },
        async loadRoomTypeCode(parent) {
            let res
            // 如果parent为空，则查询第一级菜单
            if (parent === '') {
                res = await getAction('/sys/dict/getDictItems/room_type,room_type_name,room_type_code')
            } else {
                res = await getAction('/room/roomType/queryByCode', { roomTypeCode: parent })
            }
            if (res.success) {
                // 返回的数据里必须包含 value 和 text 字段
                if (parent === '') {
                    return res.result
                } else {
                    this.rowRoomFlagList = res.result.roomFlagList
                    return res.result.roomFlagList.map(item => ({ value: item.code, text: item.name }))
                }
            }
            this.$message.warning('获取房间类型或入住模式失败: ' + res.message)
            return []
        },
        async handleValueChange(event) {
            const { type, row, column, value, target } = event
            let res
            if (column.key === "roomTypeCode" && value) {
                res = await getAction('/room/roomType/queryByCode', { roomTypeCode: value })
                if (res.success) {
                    target.setValues([{
                        rowKey: row.id,
                        values: {
                            breakfastNum: res.result.roomType.breakfastNum,
                            ratedHousePrice: res.result.roomType.roomPrice,
                            roomPrice: res.result.roomType.roomPrice * row.discount
                        }
                    }])
                }
            }
            if (column.key === "checkInMode" && value) {
                target.setValues([{
                    rowKey: row.id,
                    values: {
                        ratedHousePrice: this.rowRoomFlagList.filter(item => item.code === value)[0].price,
                        roomPrice: this.rowRoomFlagList.filter(item => item.code === value)[0].price * row.discount
                    }
                }])
            }
            if (column.key === "discount") {
                if (value < 0) {
                    this.$message.warning("折扣不能小于0")
                    target.setValues([{
                        rowKey: row.id,
                        values: {
                            discount: 0,
                        }
                    }])
                }
                target.setValues([{
                    rowKey: row.id,
                    values: {
                        roomPrice: row.ratedHousePrice * row.discount,
                    }
                }])
            }
            if (column.key === "dateArrival" || column.key === "dateDeparture") {
                const startDay = dayjs(row.dateArrival)
                const endDay = dayjs(row.dateDeparture)
                target.setValues([{
                    rowKey: row.id,
                    values: {
                        dateNum: endDay.diff(startDay, 'day'),
                    }
                }])
            }
        },
        addBefore() {
            this.roomBookInfoMxTable.dataSource = []
        },
        getAllTable() {
            let values = this.tableKeys.map(key => getRefPromise(this, key))
            return Promise.all(values)
        },
        /** 调用完edit()方法之后会自动调用此方法 */
        editAfter() {
            this.$nextTick(() => {
            })
            // 加载子表数据
            if (this.model.bookCode) {
                let params = { id: this.model.bookCode }
                this.requestSubTableData(this.url.roomBookInfoMx.list, params, this.roomBookInfoMxTable)
            }
        },
        //校验所有一对一子表表单
        validateSubForm(allValues) {
            return new Promise((resolve, reject) => {
                Promise.all([
                ]).then(() => {
                    resolve(allValues)
                }).catch(e => {
                    if (e.error === VALIDATE_FAILED) {
                        // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                        this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
                    } else {
                        console.error(e)
                    }
                })
            })
        },
        /** 整理成formData */
        classifyIntoFormData(allValues) {
            let main = Object.assign(this.model, allValues.formValue)
            return {
                ...main, // 展开
                roomBookInfoMxList: allValues.tablesValue[0].tableData,
            }
        },
        validateError(msg) {
            this.$message.error(msg)
        },

    }
}
</script>

<style scoped></style>